package com.dongbao.core.rules.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import com.dongbao.core.base.CodeRulesCommonBase;
import com.dongbao.core.rules.CodeRulesBase;
import com.dongbao.dialog.DHGToolWindow;
import com.dongbao.entity.AwardedInfo;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.java.PsiExpressionStatementImpl;
import lombok.extern.java.Log;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import com.intellij.openapi.diagnostic.Logger;
/**
 *  Sql不允许关联三张以上的表,将会影响查询效率
 * */
public class SqlJoinTableRules extends CodeRulesCommonBase implements CodeRulesBase {

    private static final Logger LOGGER = Logger.getInstance(DHGToolWindow.class);

    public SqlJoinTableRules(VirtualFile afterFile, PsiFile psiFile, Project project) {
        super(afterFile,psiFile,project);
        this.code = "未知";
        this.level = "未知";
    }

    /**
     * 执行规则判断
     * */
    @Override
    public void run(List<AwardedInfo> deduction) {
        /* 执行分析当前class是否负责当前规则 */
        try {
            printDeleteSql(deduction,afterFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printDeleteSql(List<AwardedInfo> deduction,String filepath) throws Exception{
        String namespace = "";//mybatis命名空间

        //创建一个解析器
        SAXBuilder builder = new SAXBuilder();

        //创建一个文件输入流
        InputStream in = new FileInputStream(filepath);

        //将流加载到解析器中。
        Document document = builder.build(in);

        //获取文档的根节点
        Element rootElement = document.getRootElement();

        List<Attribute> list0 = rootElement.getAttributes();
        for(Attribute attr : list0){
            if("namespace".equals(attr.getName())) {
                namespace = attr.getValue() + ".";
            }
        }
        //将根节点的所有子节点获取放到一个集合中
        List<Element> list = rootElement.getChildren();

        //循环遍历所有子节点
        for(Element element : list){
            String id = "";//sqlid
            String type = element.getName();//sql类型
            String content = element.getText();//sql内容

            //获取所有的属性,输出sqlid
            List<Attribute> list1 = element.getAttributes();
            for(Attribute attr : list1){
                if("id".equals(attr.getName())) {
                    id = attr.getValue();
                }
            }

            if(type.equals("select")){
                //判断SQL中有几个join,关联有几张表
                int sqlLength = content.length();
                String[] joinRelace = content.split(" join ");
                Integer num = joinRelace.length - 1;
                if(num>3){
//                    com.intellij.openapi.editor.Document fileDocument = PsiDocumentManager.getInstance(afterFile.getProject()).getDocument(afterFile.getContainingFile());
//                    int lineNumber = fileDocument.getLineNumber(((PsiExpressionStatementImpl) elementRow).getStartOffset());
                    packDeduction(
                            deduction,
                            afterFile.getName(),
                            afterFile.getPath(),
                            id,
                            "Sql不允许关联三张以上的表,将会影响查询效率，查询ID["+id+"]",0,0);
                }
            }

            LOGGER.info("666");
        }
    }

    @Override
    public String describe() {
        return "MyBatis";
    }
}
